package com.example.administrator.szb.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.Login;
import com.example.administrator.szb.bean.ResultBean;
import com.example.administrator.szb.bean.Yzm;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.CheckMsgUtils;
import com.example.administrator.szb.util.DialogUtil;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.SharedPreferencesUtil;
import com.example.administrator.szb.util.Toasts;
import com.example.administrator.szb.util.TokenUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.api.BasicCallback;


/**
 * Created by D N on 2017/9/9.
 */

public class RegisterActivity extends BaseActivity {
    @Bind(R.id.register_user)
    TextView registerUser;
    @Bind(R.id.register_gw)


    TextView registerGw;
    @Bind(R.id.register_user_view)
    TextView registerUserView;
    @Bind(R.id.register_gw_view)
    TextView registerGwView;
    @Bind(R.id.edit_phone_number)
    EditText editPhoneNumber;
    @Bind(R.id.edit_paseeword)
    EditText editPaseeword;
    @Bind(R.id.edit_yzm)
    EditText editYzm;
    @Bind(R.id.editText5)
    EditText editText5;
    @Bind(R.id.get_yzm)
    TextView getYzm;
    @Bind(R.id.botton_register)
    Button bottonRegister;
    @Bind(R.id.tv_user_xiyi)
    TextView tvUserXiyi;

    String phoneNumber, password, yzm, sure_paseeword;
    Toolbar toolbar;
    private static String yzm_code = "1234";//测试

    int time = 60;//获取验证码倒计时
    @Bind(R.id.backlogin)
    ImageView backlogin;
    @Bind(R.id.textView10)
    TextView textView10;

    private int type_user_or_gw = 0;//0代表用户,1代表顾问
    private ArrayList<String> register_info = new ArrayList<String>();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        // getInfo();//获取编辑框的信息
        initToolbar();//初始化toolbar
        initView();
        setTypeUserOrGw();
        SampleApplicationLike.getActivitiesInstance().add(this);
    }


    private void initView() {
        //获取验证码
        getYzm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestYzm();//发送验证码请求
            }
        });

        //注册
        bottonRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //Toasts.show(RegisterActivity.this, "onclick", Toast.LENGTH_SHORT);
                boolean isOk = checkInfo();
                if (isOk) {
                    requsetRegister();
                }

            }
        });


    }

    private boolean checkInfo() {
        getInfo();
        boolean flag = CheckMsgUtils.isMobileNO(register_info.get(0));
        if (!flag) {
            DialogUtil.showSimpleDialog(this, "手机号码格式不正确！");
        } else if (TextUtils.isEmpty(register_info.get(1))) {
            DialogUtil.showSimpleDialog(this, "请填写验证码");
        } else if (!register_info.get(1).equals(yzm_code) && !TextUtils.isEmpty(yzm_code)) {
            DialogUtil.showSimpleDialog(this, "验证码有误！");
        } else if (TextUtils.isEmpty(register_info.get(2))) {
            DialogUtil.showSimpleDialog(this, "请输入密码");
        } else if (!CheckMsgUtils.match("^[A-Za-z0-9]+", register_info.get(2)) || register_info.get(2).length() < 8) {
            DialogUtil.showSimpleDialog(this, "密码必须是8~20位的字母或数字的组合");
        } else if (TextUtils.isEmpty(register_info.get(3))) {
            DialogUtil.showSimpleDialog(this, "请输入确认密码");
        } else if (!register_info.get(2).equals(register_info.get(3))) {
            DialogUtil.showSimpleDialog(this, "两次输入的密码不一致，请重新输入！");
        } else {
            return true;
        }

        return false;
    }

    /**
     * 执行注册请求
     */
    private void requsetRegister() {

        DialogUtil.showIsoProgressbar(RegisterActivity.this,"注册中。。。");
        Map<String, String> map = new HashMap<String, String>();
        String code = TokenUtil.md5("szb").substring(0, 8);
        String pass = register_info.get(2);
        final String tel = register_info.get(0);
        map.put("code", HttpUtil.getParam());
        map.put("type", type_user_or_gw + 1 + "");//
        map.put("pass", pass);
        map.put("tel", tel);
        String url = URLAddress.URLBASE + URLAddress.URL_ZC;
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, Login.class, URLAddress.URLBASE + URLAddress.URL_ZC, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                Login result = (Login) response;
                if (result.getResult() == 0) {
                    //DialogUtil.showSimpleDialog(RegisterActivity.this, result.getErr_msg());
                    DialogUtil.dialog_ios.dismiss();
                    Toasts.show(RegisterActivity.this, "" + result.getErr_msg(), Toast.LENGTH_SHORT);
                } else {
                    result.getData().getInfo().setTel_number(register_info.get(0));
                    requestBD(result);
                    requestLoginJG(result.getData().getJpushpass());//登录极光
                    SampleApplicationLike.setUserloginInstance(result.getData());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String e = error.toString();
            }
        });

    }

    private void requestLoginJG(String pass) {
        JMessageClient.login(register_info.get(0),pass, new BasicCallback() {
            @Override
            public void gotResult(int i, String s) {
                Log.e("pdf", "gotResult: "+i+"     "+ s );
            }
        });
    }

    private void requestBD(final Login login) {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("users_id",login.getData().getId()+"");
        map.put("register_id", JPushInterface.getRegistrationID(this)+"");


        map.put("service_id",""+login.getData().getId());
        String info = GetJsonDataUtil.simpleMapToJsonStr(map);
        String url = URLAddress.URLBASE + URLAddress.URL_UP_INFO;
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, url, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean resultBean = (ResultBean) response;
                if (resultBean.getResult() == 1){
                    try {
                        //DialogUtil.showSimpleDialog(LoginNewActivity.this,"登录成功");

                        SharedPreferencesUtil.savaData(RegisterActivity.this,login.getData(),SampleApplicationLike.getKey());
                        //
                        Intent intent = new Intent(RegisterActivity.this,HomeActivity.class);

                        startActivity(intent);
                        DialogUtil.dialog_ios.dismiss();
                        //finish();


                    }catch (Exception e){
                        Toasts.show(RegisterActivity.this, ""+e.toString(), Toast.LENGTH_SHORT);
                        //DialogUtil.showSimpleDialog(RegisterActivity.this,e.toString());
                    }
                }else{
                    Toasts.show(RegisterActivity.this, ""+resultBean.getErr_msg(), Toast.LENGTH_SHORT);
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }
    /**
     * 发送获取验证码请求
     */
    private void requestYzm() {
        // TODO: 2017/9/11 获取验证码改变状态
        // getYzm.setEnabled();


        getInfo();

        if (!CheckMsgUtils.isMobileNO(register_info.get(0))) {
            DialogUtil.showSimpleDialog(this, "手机号码格式不正确");
        } else {
            changeYzmStatu();
            getYzm();
        }


    }

    /**
     * 获取验证码方法
     */
    private void getYzm() {
        Map<String, String> map = new HashMap<String, String>();
        map.put("tel", register_info.get(0));
        map.put("type", "1");//2代表注册验证码
        map.put("code", HttpUtil.getParam());
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, Yzm.class, URLAddress.URLBASE + URLAddress.URL_YZM, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                Yzm str = (Yzm) response;

                if (str.getResult() == 1) {
                    yzm_code = str.getData().getCode() + "";
                } else {
                    Toasts.show(RegisterActivity.this, "" + str.getErr_msg(), Toast.LENGTH_SHORT);
                }

                //editYzm.setText(str.getData().getCode()+"");
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                String e = error.toString();
            }
        });
    }

    /**
     * 验证码按钮状态改变60秒重新发送
     */
    private void changeYzmStatu() {
        getYzm.setEnabled(false);

        final Handler handlerTimeTask = new Handler();
        handlerTimeTask.postDelayed(new Runnable() {
            @Override
            public void run() {


                if (time <= 0) {
                    getYzm.setEnabled(true);
                    getYzm.setText("获取验证码");
                    getYzm.setTextColor(getResources().getColor(R.color.tab_choose));
                    time = 60;
                } else {
                    getYzm.setText(time + "秒后重新发送");
                    getYzm.setTextColor(getResources().getColor(R.color.gray66));
                    handlerTimeTask.postDelayed(this, 1000);
                }
                time--;
            }
        }, 1000);

    }

    /**
     * 过滤信息
     *
     * @param
     */
    private boolean fliterInfo() {
        if (register_info.get(0).equals("") || register_info.get(0) == null || register_info.get(0).length() != 11) {
            DialogUtil.showSimpleDialog(RegisterActivity.this, "手机号不能为空且为11位数字");
            return false;

        } else if (register_info.get(1).equals("") || register_info.get(1) == null) {
            DialogUtil.showSimpleDialog(RegisterActivity.this, "验证码不为空");
            return false;

        } else if (register_info.get(2).equals("") || register_info.get(2) == null) {
            DialogUtil.showSimpleDialog(RegisterActivity.this, "密码不能为空");
            return false;

        } else if (register_info.get(3).equals("") || register_info.get(3) == null) {
            DialogUtil.showSimpleDialog(RegisterActivity.this, "确认密码不能为空");
            if (register_info.get(3) != null) {
                if (register_info.get(2).equals(register_info.get(3))) {
                    DialogUtil.showSimpleDialog(RegisterActivity.this, "两次密码不一致");
                }
            }
            return false;
        }
        return true;
    }

    /**
     * 设置切换用户还是顾问
     */
    private void setTypeUserOrGw() {
        registerUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (type_user_or_gw == 1) {
                    changeStatu(type_user_or_gw);
                } else {

                }
            }
        });

        registerGw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (type_user_or_gw == 0) {
                    changeStatu(type_user_or_gw);
                } else {

                }
            }
        });
    }

    /**
     * 用于改变切换状态user or gw
     *
     * @param type_user_or_gw
     */
    private void changeStatu(int type_user_or_gw) {
        if (type_user_or_gw == 0) {
            registerGw.setTextColor(getResources().getColor(R.color.tab_choose));
            registerGwView.setVisibility(View.VISIBLE);

            registerUser.setTextColor(getResources().getColor(R.color.toolbar_home));
            registerUserView.setVisibility(View.INVISIBLE);

            this.type_user_or_gw = 1;
        } else if (type_user_or_gw == 1) {
            registerGw.setTextColor(getResources().getColor(R.color.toolbar_home));
            registerGwView.setVisibility(View.INVISIBLE);

            registerUser.setTextColor(getResources().getColor(R.color.tab_choose));
            registerUserView.setVisibility(View.VISIBLE);

            this.type_user_or_gw = 0;
        } else {

        }
    }

    private void initToolbar() {
        //View view = findViewById(R.id.include);
        toolbar = (Toolbar) findViewById(R.id.register_toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
        actionBar.setTitle("");
        toolbar.setBackgroundColor(getResources().getColor(R.color.white));
    }


    /**
     * 获取输入框的信息 放入register_info 集合中。
     */
    private void getInfo() {

        register_info.clear();
        phoneNumber = editPhoneNumber.getText().toString().trim();
        password = editPaseeword.getText().toString().trim();
        yzm = editYzm.getText().toString().trim();
        sure_paseeword = editText5.getText().toString().trim();

        register_info.add(phoneNumber);
        register_info.add(yzm);
        register_info.add(password);
        register_info.add(sure_paseeword);


    }


    @OnClick({R.id.backlogin, R.id.tv_user_xiyi})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backlogin:
                finish();
                break;
            case R.id.tv_user_xiyi:
                Intent intent = new Intent(RegisterActivity.this,GZXYActivity.class);//额，
                intent.putExtra("title","市值宝服务协议");
                intent.putExtra("id",4);
                startActivity(intent);
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
